"""
API配置管理模块
用于管理各种模型API的配置
"""

import os
from typing import Dict, Optional
from dataclasses import dataclass

@dataclass
class APIConfig:
    """API配置数据类"""
    provider: str # 服务提供商 (如 openai, anthropic, ollama, openrouter 等)
    api_key: str
    base_url: Optional[str] = None # 自定义基础URL
    default_model: str = "gpt-3.5-turbo"  # 默认模型

class ConfigManager:
    """配置管理器"""
    
    def __init__(self):
        self.configs: Dict[str, APIConfig] = {}
        self._load_configs()
    
    def _load_configs(self):
        """从环境变量或配置文件加载API配置"""
        # 从环境变量加载配置
        # 优先使用开源模型配置
        ollama_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
        if ollama_url:
            self.configs["ollama"] = APIConfig(
                provider="ollama",
                api_key="",  # Ollama通常不需要API密钥
                base_url=ollama_url,
                default_model=os.getenv("OLLAMA_MODEL", "llama3.2")
            )
        
        # OpenRouter配置（支持多种开源模型）
        openrouter_api_key = os.getenv("OPENROUTER_API_KEY")
        if openrouter_api_key:
            self.configs["openrouter"] = APIConfig(
                provider="openrouter",
                api_key=openrouter_api_key,
                base_url="https://openrouter.ai/api/v1",
                default_model=os.getenv("OPENROUTER_MODEL", "nousresearch/hermes-3-llama-3.1-405b:free")
            )
        
        # 为Ollama配置正确格式的模型名称
        if "ollama" in self.configs:
            # 确保Ollama模型名称以"ollama/"开头
            if not self.configs["ollama"].default_model.startswith("ollama/"):
                self.configs["ollama"].default_model = f"ollama/{self.configs['ollama'].default_model}"
        
        # OpenAI配置
        openai_api_key = os.getenv("OPENAI_API_KEY")
        if openai_api_key:
            self.configs["openai"] = APIConfig(
                provider="openai",
                api_key=openai_api_key,
                base_url=os.getenv("OPENAI_BASE_URL"),
                default_model=os.getenv("OPENAI_MODEL", "gpt-4o-mini")
            )
        
        # Anthropic配置
        anthropic_api_key = os.getenv("ANTHROPIC_API_KEY")
        if anthropic_api_key:
            self.configs["anthropic"] = APIConfig(
                provider="anthropic",
                api_key=anthropic_api_key,
                default_model=os.getenv("ANTHROPIC_MODEL", "claude-3-haiku-20240307")
            )
    
    def get_config(self, service_name: str) -> Optional[APIConfig]:
        """获取特定服务的配置"""
        return self.configs.get(service_name)
    
    def add_config(self, service_name: str, config: APIConfig):
        """添加新的配置"""
        self.configs[service_name] = config
    
    def get_available_services(self) -> list:
        """获取可用服务列表"""
        return list(self.configs.keys())
    
    def has_service(self, service_name: str) -> bool:
        """检查服务是否已配置"""
        return service_name in self.configs

# 全局配置管理器实例
config_manager = ConfigManager()

def get_config_for_service(service_name: str) -> Optional[APIConfig]:
    """获取指定服务的配置"""
    return config_manager.get_config(service_name)

def get_available_services() -> list:
    """获取所有已配置的服务"""
    return config_manager.get_available_services()

def has_service(service_name: str) -> bool:
    """检查服务是否已配置"""
    return config_manager.has_service(service_name)
